package com.kuangstudy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kuangstudy.config.exception.BusinessException;
import com.kuangstudy.config.results.Code;
import com.kuangstudy.config.results.Result;
import com.kuangstudy.entity.User;
import com.kuangstudy.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping
    public Result save(User user) {
        boolean flag = userService.saveOrUpdate(user);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERROR);
    }

    @PutMapping
    public Result update(User user) {
        boolean flag = userService.updateById(user);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERROR);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = userService.removeById(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERROR);
    }

    @GetMapping("/{id}")
    public Result get(@PathVariable("id") Integer id) {
        User user = userService.getById(id);
        //模拟出现异常，使用条件控制，便于测试结果
        if (id == 10) throw new BusinessException("查询出错啦，请重试！", Code.GET_ERROR);
        return new Result(null != user ? Code.GET_OK : Code.GET_ERROR, user);
    }

    @GetMapping("/{pageNo}/{pageSize}")
    public Result getAll(@PathVariable Integer pageNo, @PathVariable Integer pageSize) {
        // 1: 设置分页
        Page<User> page = new Page<>(pageNo, pageSize);
        // 2: 设置条件
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 3：查询分页返回
        IPage<User> page1 = userService.page(page, lambdaQueryWrapper);
        return new Result(null != page1 ? Code.GET_OK : Code.GET_ERROR, page1);
    }

}
